<?php
/**
 * 数据权限控制器
 * 处理数据权限相关的HTTP请求
 */

declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use app\service\DataPermissionService;
use think\facade\Request;
use think\response\Json;

class DataPermissionController extends BaseController
{
    protected $permissionService;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        $this->permissionService = new DataPermissionService();
    }

    /**
     * 获取用户数据权限信息
     * @return Json
     */
    public function getUserPermissions(): Json
    {
        try {
            $params = Request::param();
            $userId = (int)($params['user_id'] ?? 0);
            $module = trim($params['module'] ?? '');

            if ($userId <= 0) {
                $userId = $this->getUserId();
            }

            if ($userId <= 0) {
                return $this->error('用户ID不能为空', 400);
            }

            $permissions = $this->permissionService->getUserDataPermissions($userId, $module);

            return $this->success($permissions, '获取用户权限成功');
        } catch (\Exception $e) {
            return $this->error('获取用户权限失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取数据权限配置
     * @return Json
     */
    public function getPermissionConfig(): Json
    {
        try {
            $params = Request::param();
            $module = trim($params['module'] ?? '');

            if (empty($module)) {
                return $this->paramError('模块名称不能为空');
            }

            $config = $this->permissionService->getModulePermissionConfig($module);

            return $this->success($config, '获取权限配置成功');
        } catch (\Exception $e) {
            return $this->error('获取权限配置失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 测试数据权限查询条件
     * @return Json
     */
    public function testPermissionConditions(): Json
    {
        try {
            $params = Request::param();
            $userId = (int)($params['user_id'] ?? 0);
            $module = trim($params['module'] ?? '');

            if ($userId <= 0) {
                $userId = $this->getUserId();
            }

            if ($userId <= 0) {
                return $this->error('用户ID不能为空', 400);
            }

            if (empty($module)) {
                return $this->paramError('模块名称不能为空');
            }

            $conditions = $this->permissionService->buildPermissionConditions($userId, $module);

            return $this->success([
                'user_id' => $userId,
                'module' => $module,
                'conditions' => $conditions,
                'sql_where' => $this->formatConditionsForDisplay($conditions)
            ], '生成权限条件成功');
        } catch (\Exception $e) {
            return $this->error('生成权限条件失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 检查用户对特定数据的权限
     * @return Json
     */
    public function checkDataAccess(): Json
    {
        try {
            $params = Request::param();
            $userId = (int)($params['user_id'] ?? 0);
            $module = trim($params['module'] ?? '');
            $dataId = (int)($params['data_id'] ?? 0);

            if ($userId <= 0) {
                $userId = $this->getUserId();
            }

            if ($userId <= 0) {
                return $this->error('用户ID不能为空', 400);
            }

            if (empty($module)) {
                return $this->paramError('模块名称不能为空');
            }

            if ($dataId <= 0) {
                return $this->paramError('数据ID不能为空');
            }

            $hasAccess = $this->permissionService->checkDataAccess($userId, $module, $dataId);

            return $this->success([
                'user_id' => $userId,
                'module' => $module,
                'data_id' => $dataId,
                'has_access' => $hasAccess
            ], '权限检查完成');
        } catch (\Exception $e) {
            return $this->error('权限检查失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新数据共享权限
     * @return Json
     */
    public function updateSharePermission(): Json
    {
        try {
            $params = Request::param();
            $module = trim($params['module'] ?? '');
            $dataId = (int)($params['data_id'] ?? 0);
            $shareUserIds = $params['share_user_ids'] ?? [];
            $operatorId = $this->getUserId();

            if (empty($module)) {
                return $this->paramError('模块名称不能为空');
            }

            if ($dataId <= 0) {
                return $this->paramError('数据ID不能为空');
            }

            if ($operatorId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            // 检查操作权限
            $hasPermission = $this->permissionService->checkDataAccess($operatorId, $module, $dataId);
            if (!$hasPermission) {
                return $this->error('无权限操作此数据', 403);
            }

            $result = $this->permissionService->updateSharePermission($module, $dataId, $shareUserIds, $operatorId);

            return $this->success($result, '更新共享权限成功');
        } catch (\Exception $e) {
            return $this->error('更新共享权限失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取部门数据权限统计
     * @return Json
     */
    public function getDepartmentStats(): Json
    {
        try {
            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $stats = $this->permissionService->getDepartmentStats($userId);

            return $this->success($stats, '获取部门统计成功');
        } catch (\Exception $e) {
            return $this->error('获取部门统计失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取可共享的用户列表
     * @return Json
     */
    public function getShareableUsers(): Json
    {
        try {
            $params = Request::param();
            $keyword = trim($params['keyword'] ?? '');
            $departmentId = (int)($params['department_id'] ?? 0);
            $userId = $this->getUserId();

            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $users = $this->permissionService->getShareableUsers($userId, $keyword, $departmentId);

            return $this->success($users, '获取用户列表成功');
        } catch (\Exception $e) {
            return $this->error('获取用户列表失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 清除用户权限缓存
     * @return Json
     */
    public function clearPermissionCache(): Json
    {
        try {
            $params = Request::param();
            $userId = (int)($params['user_id'] ?? 0);
            $currentUserId = $this->getUserId();

            if ($currentUserId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            // 只允许管理员或自己清除缓存
            if ($userId > 0 && $userId !== $currentUserId && $currentUserId !== 1) {
                return $this->error('无权限清除其他用户的缓存', 403);
            }

            $targetUserId = $userId > 0 ? $userId : $currentUserId;
            $this->permissionService->clearUserPermissionCache($targetUserId);

            return $this->success('清除权限缓存成功');
        } catch (\Exception $e) {
            return $this->error('清除权限缓存失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 格式化条件用于显示
     * @param array $conditions
     * @return array
     */
    private function formatConditionsForDisplay(array $conditions): array
    {
        $formatted = [];
        
        foreach ($conditions as $condition) {
            if (is_array($condition) && count($condition) >= 2) {
                $field = $condition[0];
                $operator = $condition[1];
                $value = $condition[2] ?? '';
                
                if ($operator === 'in' && is_array($value)) {
                    $formatted[] = "{$field} IN (" . implode(',', $value) . ")";
                } else {
                    $formatted[] = "{$field} {$operator} {$value}";
                }
            }
        }
        
        return $formatted;
    }
}